package www.core.com.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import www.core.com.dao.BaseDAO;
import www.core.com.pojo.Groupperson;
import www.core.com.service.IGroupPersonService;

@Service("groupPersonService")
@org.springframework.transaction.annotation.Transactional
public class GroupPersonServiceImpl implements IGroupPersonService {

	@Resource(name = "hibernateDAO")
	BaseDAO<Groupperson> hibernateDAO;

	public GroupPersonServiceImpl() {
		// TODO Auto-generated constructor stub
	}


	public boolean isUserInGroup(Integer groupid, Integer userid) {
		if (groupid == null || userid == null) {
			return false;
		}

		String hql = "select count(*) from " + Groupperson.class.getSimpleName()
				+ " gp where gp.group.id = :groupid and  gp.user.id = :userid ";
		Map map = new HashMap();
		map.put("groupid", groupid);
		map.put("userid", userid);

		Long count = hibernateDAO.count(hql, map);
		if (count == 0) {
			return false;
		}
		return true;
	}
	
	public void lock(Groupperson person){
		hibernateDAO.jdbcSelectLock("select * from sysgroup where id="+person.getGroup().getId());
	}
	@Override
	public Groupperson add(Groupperson person) {
		// TODO Auto-generated method stub
		lock(person);
		hibernateDAO.jdbcUpdate("update sysgroup set foucsPersonNum=foucsPersonNum+1 where id = "+person.getGroup().getId()+" ");
		hibernateDAO.save(person);
		return person;
	}

	public Groupperson delete(Groupperson person) {
		// TODO Auto-generated method stub
		lock(person);
		hibernateDAO.jdbcUpdate("update sysgroup set foucsPersonNum=foucsPersonNum-1 where id = "+person.getGroup().getId());
		hibernateDAO.delete(person);
		return person;
	}
	public Groupperson deleteIsNoLock(Groupperson person) {
		// TODO Auto-generated method stub
		hibernateDAO.jdbcUpdate("update sysgroup set foucsPersonNum=foucsPersonNum-1 where id = "+person.getGroup().getId());
		hibernateDAO.delete(person);
		return person;
	}

	@Override
	public Groupperson getUserInGroup(Integer groupid, Integer userid) {
		Map<String, Integer> map = new HashMap<String,Integer>();
		map.put("groupid", groupid);
		map.put("userid", userid);
		Groupperson result = hibernateDAO.findByColumn("from "+Groupperson.class.getSimpleName()+" where groupid=:groupid and userId=:userid", map);
		return result;
	}
}
